import csv
import urllib.request
import time
import os

# 读取CSV文件中的IP地址
def read_ips_from_csv(file_path):
    ips = []
    try:
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                reader = csv.reader(f)
                for row in reader:
                    if row and row[0].strip():
                        ip = row[0].strip()
                        ips.append(ip)
            print(f"从CSV文件读取到 {len(ips)} 个IP地址")
        else:
            print(f"错误：未找到CSV文件: {file_path}")
    except Exception as e:
        print(f"读取CSV文件时出错: {e}")
    return ips

# 检测单个IP是否可用
def check_ip(ip, timeout=5):
    try:
        # 记录开始时间
        start_time = time.time()
        
        # 创建代理处理器
        proxy_handler = urllib.request.ProxyHandler({
            'http': f'http://{ip}',
            'https': f'https://{ip}'
        })
        
        # 创建opener
        opener = urllib.request.build_opener(proxy_handler)
        opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
        
        # 设置超时
        urllib.request.install_opener(opener)
        request = urllib.request.Request('https://www.baidu.com/')
        
        # 发送请求
        response = urllib.request.urlopen(request, timeout=timeout)
        
        # 计算响应时间
        response_time = time.time() - start_time
        
        # 检查状态码
        if response.status == 200:
            return ip, True, response_time
        else:
            return ip, False, response_time
    except Exception as e:
        # 捕获所有异常，表示IP不可用
        print(f"IP {ip} 检测失败: {str(e)[:100]}...")
        return ip, False, None

# 逐个检测IP可用性
def check_all_ips(ips):
    available_ips = []
    unavailable_ips = []
    
    for i, ip in enumerate(ips):
        print(f"正在检测: {i+1}/{len(ips)}, IP: {ip}")
        result_ip, is_available, response_time = check_ip(ip)
        
        if is_available:
            available_ips.append({'IP': result_ip, '响应时间(秒)': response_time})
            print(f"IP {ip} 可用，状态码: 200，响应时间: {response_time:.2f}秒")
        else:
            unavailable_ips.append({'IP': result_ip})
            print(f"IP {ip} 不可用")
    
    return available_ips, unavailable_ips

# 保存结果到CSV文件
def save_results_to_excel(available_ips, unavailable_ips):
    # 保存可用IP
    if available_ips:
        with open('可用IP.csv', 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            # 写入表头
            writer.writerow(['IP', '响应时间(秒)'])
            # 写入数据
            for item in available_ips:
                writer.writerow([item['IP'], item['响应时间(秒)']])
        print(f"可用IP已保存到 '可用IP.csv'，共 {len(available_ips)} 个")
    else:
        print("没有可用的IP")
    
    # 保存不可用IP
    if unavailable_ips:
        with open('不可用IP.csv', 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            # 写入表头
            writer.writerow(['IP'])
            # 写入数据
            for item in unavailable_ips:
                writer.writerow([item['IP']])
        print(f"不可用IP已保存到 '不可用IP.csv'，共 {len(unavailable_ips)} 个")
    else:
        print("没有不可用的IP")

# 主函数
def main():
    print("开始IP检测...")
    
    # 读取IP地址
    csv_file_path = 'sample_ips.csv'
    ips = read_ips_from_csv(csv_file_path)
    
    # 如果没有读取到IP，让用户手动输入几个进行测试
    if not ips:
        print("\n未读取到IP地址，让我们手动测试几个IP:")
        ips = ['8.8.8.8', '1.1.1.1', '208.67.222.222']  # 一些公共DNS服务器IP
    
    if not ips:
        print("没有找到IP地址")
        return
    
    print(f"共读取到 {len(ips)} 个IP地址")
    
    # 检测所有IP
    available_ips, unavailable_ips = check_all_ips(ips)
    
    # 保存结果
    save_results_to_excel(available_ips, unavailable_ips)
    
    print("IP检测完成！")

if __name__ == "__main__":
    main()